<?php
/**
 * 连接MQ采用Stomp协议
 * User: allen_ios
 * Date: 17/1/11
 * Time: 下午3:59
 */

namespace Task\Core;


class MqStomp
{
    /**
     * @var 类实例的静态属性
     */
    private static $_instance;

    private function __construct()
    {

    }

    /**
     * 获得实例对象
     */
    public static function getInstance($mqConfig = array())
    {
        if ( !(self::$_instance instanceof self) ) {	//判断实例是否被创建，如果未被创建
            self::$_instance = self::connectStomp($mqConfig);
        }

        return self::$_instance;
    }

    private static function connectStomp($mqConfig = array())
    {
        //设置mq配置
        $defOption = array(
            'mq_ip' => config('mq_ip') ? : '127.0.0.1',
            'mq_port' => config('mq_port') ? : '61613'
        );
        if (empty($mqConfig)) {
            $mqConfig = $defOption;
        } else {
            $mqConfig = array_merge($defOption,$mqConfig);
        }

        //连接信息
        $linkInfo = "tcp://".$mqConfig['mq_ip'].':'.$mqConfig['mq_port'];

        //连接Activemq
        try {
            $stomp = new \Stomp($linkInfo);
            return $stomp;
        } catch(\StompException $ex) {
            wLog('Connection failed: ' . $ex->getMessage(),'StompError');
            exit();
        }
    }

    /**
     * 防止对象被克隆
     */
    public function __clone()
    {
        throw new \Exception('单列对象不能被克隆');
    }


    /**
     * 销毁对象
     */
    private function __destruct()
    {
        unset(self::$_instance);
    }
}